package com.ylkj.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SpellProxyUtil {
    private static Log logger = LogFactory.getLog(SpellProxyUtil.class);
    /**
    * @Description:将汉字转换为拼音
    * @param source
    * @return 拼音。如：你好，nihao
    * @Author：NIECHW
    * @CreateDate：2016-09-20 下午07:23:35
    * @Update:
    * @UpdateDate:
    * @UpdateDescription:
     */
    public static String convertWordToSpell(String source) {
        String convert = "";
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        for (int i = 0, l = source.length(); i < l; i++) {
            char word = source.charAt(i);
            
            String[] pinyinArray = null;
            try {
                pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word,
                        outputFormat);
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                logger.warn(e.getMessage(), e);
            }

            if (pinyinArray != null && pinyinArray.length > 0) {
            	if ( String.valueOf(word).equals("区") ) {
            		 convert += pinyinArray[1];
            	} else {
            		 convert += pinyinArray[0];	
            	}
               
            } else {
                convert += word;
            }

        }
        return convert;
    }
    
    /**
    * @Description:将一串汉字的每个字转换为首字母
    * @param source
    * @return 首字母串。如：你好，nh
    * @Author：NIECHW
    * @CreateDate：2016-09-20 下午07:28:58
    * @Update:
    * @UpdateDate:
    * @UpdateDescription:
     */
    public static String convertWordToInitial(String source) {
        String convert = "";
        for (int i = 0, l = source.length(); i < l; i++) {
            char word = source.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null && pinyinArray.length > 0) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }
}
